package com.mycookbook;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.IBinder;
import android.os.SystemClock;
import android.widget.Toast;

public class Alarm extends Service
{
	private static final int MY_NOTIFICATION_ID=1;
	private NotificationManager notificationManager;
	private Notification myNotification;
	
	@Override
	public void onStart(Intent intent, int startId)
	{
		super.onStart(intent, startId);
		
		String msg = intent.getExtras().getString("1");
		StartAlarmByInput(msg);
	}
	
	private void StartAlarmByInput(String msg)
	{
		//Change the value input from ms to s
		int seconds = 1000*Integer.parseInt(msg);
		
		//This broadcast receiver will be started from the alarm manager
		final BroadcastReceiver receiver = new BroadcastReceiver()
		{
			@Override
			public void onReceive(Context context, Intent intent)
			{
				DisplayNotification();
			}
		};
		
		//Setup the broadcast receiver function something
		this.registerReceiver(receiver,  new IntentFilter("Alarm"));
		PendingIntent pintent = PendingIntent.getBroadcast(this, 0, new Intent("Alarm"), 0);
		
		//Setup the alarm manager and
		AlarmManager am = (AlarmManager)(this.getSystemService(Context.ALARM_SERVICE));
		am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + seconds, pintent);
	}
	
	private void DisplayNotification()
	{
		String notificationText = "Food is ready!";
		String notificationTitle = "My Cookbook";
		
		notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
		myNotification = new Notification(R.drawable.ic_launcher,"Food is ready!", System.currentTimeMillis());
		Context context = getApplicationContext();
		   
		Intent myIntent = new Intent(this, MainActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, myIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
		
		myNotification.defaults |= Notification.DEFAULT_SOUND;
		myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
		myNotification.setLatestEventInfo(context, notificationTitle, notificationText, pendingIntent);
		notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
}
